# Contributor: psykose <alice@ayaya.dev>
# Contributor: Alex Yam <alex@alexyam.com>
# Maintainer: psykose <alice@ayaya.dev>
pkgname=wasi-compiler-rt
# match llvm ver
pkgver=14.0.6
_llvmver="${pkgver%%.*}"
_wasi_sdk_ver=16
pkgrel=0
pkgdesc="WASI LLVM compiler runtime"
url="https://compiler-rt.llvm.org/"
arch="all"
options="!check" # TODO: check
license="Apache-2.0 WITH LLVM-exception BSD-2-Clause"
makedepends="
	clang
	cmake
	libxml2-dev
	llvm$_llvmver-dev
	llvm$_llvmver-static
	python3-dev
	samurai
	wasi-libc
	zlib-dev
	"
source="https://github.com/llvm/llvm-project/releases/download/llvmorg-$pkgver/compiler-rt-$pkgver.src.tar.xz
	https://github.com/llvm/llvm-project/releases/download/llvmorg-$pkgver/llvm-$pkgver.src.tar.xz
	https://github.com/WebAssembly/wasi-sdk/archive/refs/tags/wasi-sdk-$_wasi_sdk_ver.tar.gz
	"
builddir="$srcdir"/wasi-compiler-rt

prepare() {
	default_prepare
	mkdir -p "$builddir"
	mv "$srcdir"/compiler-rt-$pkgver.src "$builddir"/compiler-rt
	mv "$srcdir"/llvm-$pkgver.src "$builddir"/llvm
	mv "$srcdir"/wasi-sdk-wasi-sdk-$_wasi_sdk_ver/wasi-sdk.cmake "$builddir"
	mv "$srcdir"/wasi-sdk-wasi-sdk-$_wasi_sdk_ver/cmake "$builddir"
	mv "$srcdir"/cmake/* "$builddir"/cmake
}

build() {
	export CFLAGS="$CFLAGS -fno-exceptions --sysroot=/usr/share/wasi-sysroot"
	cmake -B build -G Ninja \
		-DCMAKE_BUILD_TYPE=MinSizeRel \
		-DCMAKE_MODULE_PATH="$builddir"/cmake \
		-DCMAKE_TOOLCHAIN_FILE="$builddir"/wasi-sdk.cmake \
		-DCMAKE_C_COMPILER_WORKS=ON \
		-DCOMPILER_RT_BAREMETAL_BUILD=ON \
		-DCOMPILER_RT_INCLUDE_TESTS=OFF \
		-DCOMPILER_RT_HAS_FPIC_FLAG=OFF \
		-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON \
		-DCOMPILER_RT_OS_DIR=wasi \
		-DWASI_SDK_PREFIX=/usr \
		-DCMAKE_INSTALL_PREFIX=/usr/lib/clang/$pkgver/ \
		compiler-rt/lib/builtins
	cmake --build build
}

package() {
	DESTDIR="$pkgdir" cmake --install build
}
sha512sums="
c0e63071cb99bca837b83fd0e3597cf45cc635f73ab88a1ec48e863a1633f42bd402ea7c5130e8fa0f550b9574c1ecac1799b92b789565e4ead955cf60060907  compiler-rt-14.0.6.src.tar.xz
6461bdde27aac17fa44c3e99a85ec47ffb181d0d4e5c3ef1c4286a59583e3b0c51af3c8081a300f45b99524340773a3011380059e3b3a571c3b0a8733e96fc1d  llvm-14.0.6.src.tar.xz
501467cb04ee85ab2ccc3d8ab1beb5dd8957ca71cc51c86fd357991ddccb1a8c2656e24b947ea3a5acfaafd8c762f5ba20458c22b58a5a5c85ef8ecb7a76db65  wasi-sdk-16.tar.gz
"
